<template>
  <div style="display: inline-block;text-align: left;">
    <el-button type="primary" size="small" @click="addUser()">{{
      $t("table.add")
    }}</el-button>
    <el-dialog v-if="dialogTableVisible" :before-close="closeDia" :visible.sync="dialogTableVisible" top="1%" :title="$t('table.add')" width="40%">
      <el-form ref="formData" :model="formData" :rules="rules" reset-field label-position="right" label-width="auto">
        <el-form-item :label="$t('table.worker_name')" prop="name">
          <el-col>
            <el-input v-model="formData.name" label="right" type="text" />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('table.worker_id')" prop="person_id">
          <el-col>
            <el-input v-model="formData.person_id" label="right" type="text" />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('staff.employee_card_id')" prop="employee_card_id">
          <el-col>
            <el-input v-model="formData.employee_card_id" label="right" type="text" />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('table.avatar')" prop="face_pic">
          <el-alert :title="$t('staff.img_tip')" type="warning" show-icon
            style="margin-bottom: 10px; line-height: 20px; width: 380px" :close-text="$t('staff.know')" />
          <el-upload :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :http-request="img_update"
            class="avatar-uploader" action="">
            <img v-if="face_pic" :src="face_pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <!-- <el-form-item :label="$t('staff.img_enc')" prop="image_enc">
          <el-select v-model="formData.image_enc" :placeholder="$t('validation.is_encrypt')">
            <el-option :label="$t('staff.yes')" value="true" />
            <el-option :label="$t('staff.no')" value="false" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item :label="$t('staff.sex')" prop="gender">
          <el-select
            v-model="formData.gender"
          >
            <el-option :label="$t('staff.man')" value="1" />
            <el-option :label="$t('staff.women')" value="0" />
          </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('table.company')" prop="company_id">
          <el-select v-model="formData.company_id" @visible-change="departmentNull" @change="CompanyIndex(formData.company_id)">
            <el-option v-for="(item, index) in Company_list" :key="index" :label="item.company" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.department')" prop="id">
          <el-select v-model="formData.id" clear @change="departmentIndex(formData.id)">
            <el-option v-for="(item, index) in department_list" :key="index" :label="item.department" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item :label="$t('staff.permiss_role')" prop="shop_role_id">
          <el-select
            v-model="formData.shop_role_id"
          >
            <el-option
              v-for="(item, index) in rolePermissions"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item :label="$t('staff.shcedule')" prop="schedule_id">
          <el-select v-model="formData.schedule_id">
            <el-option v-for="(item, index) in defaultShift" :key="index" :label="item.name" :value="item.schedule_id" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item :label="$t('staff.is_departure')" prop="partment">
          <el-select v-model="formData.quit">
            <el-option :label="$t('staff.yes')" value="1" />
            <el-option :label="$t('staff.no')" value="0" />
          </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('table.remark')" prop="description">
          <el-col >
            <el-input v-model="formData.description" label="right" type="text" />
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('staff.access_authorization')" prop="atclik">
          <el-select ref="refSubCat" v-model="formData.atclik" multiple>
            <!-- <el-option :label="$t('staff.all_device')" value="*" /> -->
            <el-option v-for="(item, index) in Equipment" :key="index" :label="item.device_name" :value="item.sn" />
          </el-select>
        </el-form-item>
        <el-form-item align="right">
          <div>
            <el-button type="primary" size="small" @click="submitForm()">{{
              $t("table.complete")
            }}</el-button>
            <el-button size="small" @click="closeDia()">{{
              $t("table.cancel")
            }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import {
  employee_add,
  department_get_select,
  push_get_list,
} from "@/api/user_manage/user_manage";
import { client } from "@/utils/alioss";
import { get_list } from "@/api/organization_manage/organization_manage";

// 获取默认班次
import { get_schedule_list } from "@/api/attendance_management/attendanceShift";

// 角色数据
import { getList } from "@/api/shop_admin_auth/shopRole.js";

export default {
  props: {
    row_id: {
      type: Number,
      default: function () {
        return null;
      },
    },
  },
  data() {
    return {
      widthsize: null,
      heightsize: null,
      EquipmentList: [],
      atclik: [],
      labelname: null,
      deviceAuthList: null,
      count: "0",
      is_all: false,
      Equipment: [],
      Companyname: null,
      newTime: null,
      department_list: null,
      Company_list: null,
      // 多选框
      checkAll: false,
      isIndeterminate: true,
      defaultShift: null,
      checkList: [],
      face_pic: "",
      dialogTableVisible: false,
      company_id: null,
      department_id: null,
      base64type: null,
      rolePermissions: null,
      company_id_id: null,
      formData: {
        atclik:''
      },
      base64: null,
      rules: {
        person_id: [
          {
            required: true,
            message: this.$t("validation.worker_id"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("validation.worker_name"),
            trigger: "blur",
          },
        ],
        // company_id: [
        //   {
        //     required: true,
        //     message: this.$t("validation.company"),
        //     trigger: "blur"
        //   }
        // ],
        // employee_card_id: [
        //   {
        //     required: true,
        //     message: this.$t("validation.employee_card"),
        //     trigger: "blur"
        //   }
        // ],
        // image_enc: [
        //   {
        //     required: true,
        //     message: this.$t("validation.is_encrypt"),
        //     trigger: "blur"
        //   }
        // ],
        // id: [
        //   {
        //     required: true,
        //     message: this.$t("validation.employee_card"),
        //     trigger: "blur"
        //   }
        // ],
        // face_pic: [{ required: true, message: '请填入头像'}],
        // shop_role_id: [
        //   {
        //     required: true,
        //     message: this.$t("validation.role"),
        //     trigger: "blur"
        //   }
        // ],
        // schedule_id: [
        //   {
        //     required: true,
        //     message: this.$t("validation.shcedule"),
        //     trigger: "blur"
        //   }
        // ],
        // image_type: [
        //   { required: true, message: "请输入图片格式", trigger: "blur" }
        // ]
        atclik: [
          { required: true, message: this.$t("staff.access_authorization"), trigger: 'blur' }
        ]
      },
    };
  },
  // watch: {
  //   atclik: function(val, oldval) {
  //     let newindex = val.indexOf('*'),
  //       oldindex = oldval.indexOf('*')
  //     if (newindex != -1 && oldindex == -1 && val.length > 1) {
  //       this.atclik = ['*']
  //     } else if (newindex != -1 && oldindex != -1 && val.length > 1) {
  //       this.atclik.splice(val.indexOf('*'), 1)
  //     }
  //   }
  // },
  created() {
    this.time();
  },
  methods: {
    // 当前时间
    time() {
      var date = new Date();
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();
      var h = date.getHours();
      var mm = date.getMinutes() + 1;
      var s = date.getSeconds() + 1;
      this.newTime = `${y}-${m}-${d} ${h}:${mm}:${s} `;
      console.log(this.newTime, "time");
    },
    // 关闭弹窗
    closeDia() {
      this.dialogTableVisible = false;
    },
    // selectAll(val) {
    //   console.log(val, 'val')
    //   // console.log(val,'vvvvvvvvvvvvv');
    //   // if (val.filter(item => {return item === "*"; })[0]) {
    //   //   this.atclik = ["*"];
    //   //   this.Equipment.forEach(equ => {
    //   //     this.atclik.push(equ.sn);
    //   //   });
    //   // }
    //   if (
    //     val.filter(item => {
    //       return item === '*'
    //     })[0]
    //   ) {
    //     const data = {
    //       sn: '*',
    //       count: '-1'
    //     }
    //     this.EquipmentList.push(data)
    //   }
    // },

    // 上传图片开始 =========================
    handleAvatarSuccess(res, file) {
      this.face_pic = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const that = this;
      console.log(file, "flie");
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      const img = new Image();
      console.log(img, "img");
      var reader = new FileReader();
      reader.onload = (e) => {
        img.src = e.target.result;
        img.onload = function () {
          var widthid = this.width;
          console.log(widthid, "wwwwwwwwwwwwwwwwwwwwww");
        };
      };
      console.log(this.widthsize,'this.widthsizekuan')
      
      if (!isJPG) {
        this.$message.error(this.$t("validation.img_tip1"));
      }
      if (!isLt2M) {
        this.$message.error(this.$t("validation.img_tip2"));
      }
      // console.log(that.widthsize,'宽度1111')

      // console.log(this.width,'宽度')
      return isJPG && isLt2M;
    },
    img_update(file) {
      const that = this;
      var fileName = "banner_img" + file.file.uid;
      client()
        .put(fileName, file.file)
        .then((result) => {
          if (this.widthsize < 750 || this.heightsize < 750) {
          this.$message.error(this.$t("validation.img_tip3"));
          }
          this.face_pic = result.url;
          that.img = result.url;
          // this.$message.success("图片上传成功！");
        });
      // 获取base64
      var reader = new FileReader();
      // 创建一个img对象
      var img = new Image();
      reader.readAsDataURL(file.file);
      reader.onload = (e) => {
        // this.base64 = reader.result.split(",")[1];
        this.base64type = reader.result.split(",")[0];

        img.src = e.target.result;
        // base64地址图片加载完毕后执行
        img.onload = function () {
          // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
          var canvas = document.createElement("canvas");
          var context = canvas.getContext("2d");
          // 图片原始尺寸
          var originWidth = this.width;
          that.widthsize = originWidth;
          var originHeight = this.height;
          that.heightsize = originHeight;
           

          // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
          var maxWidth = 300,
            maxHeight = 300;
          // 目标尺寸
          var targetWidth = originWidth,
            targetHeight = originHeight;
          // 图片尺寸超过最大尺寸的限制
          if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
              // 更改宽度，按照宽度限定尺寸
              targetWidth = maxWidth;
              targetHeight = Math.round(
                maxWidth * (originHeight / originWidth)
              );
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(
                maxHeight * (originWidth / originHeight)
              );
            }
          }
          // 对图片进行缩放
          canvas.width = targetWidth;
          // console.log( canvas.width,' canvas.width')
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
          /* 第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
          // 压缩后的base64文件
          var newUrl = canvas.toDataURL("image/jpeg", 0.92);
          that.base64 = newUrl.split(",")[1];
          that.face_pic = that.base64;
          that.base64type = newUrl.split(",")[0];
          // console.log(newUrl, '0000000000000000000000000000000')
        };
      };
    },

    // 上传图片结束  =========================

    // 添加按钮
    addUser(formData) {
      (this.formData = {}), (this.face_pic = ""), (this.Equipment = [""]);
      this.dialogTableVisible = true;
      get_list(store.getters.token).then((res) => {
        this.Company_list = res.data.list.data;
        console.log(this.Company_list, "Company_list");
      });
      // 默认班次数据
      get_schedule_list(store.getters.token).then((res) => {
        this.defaultShift = res.data.list.data;
      });
      // 角色权限数据
      getList(store.getters.token).then((res) => {
        this.rolePermissions = res.data.list.data;
      });
      // 获取设备名称
      push_get_list(store.getters.token).then((res) => {
        console.log(res, "rrraa");
        this.Equipment = res.data.list.data;
      });
    },

    // 部门数据
    CompanyIndex(id) {
      department_get_select(store.getters.token, { company_id: id }).then(
        (res) => {
          this.department_list = res.data.list;
          console.log(this.department_list, "this,department_list");
          console.log(res, "res.data.list");
        }
      );
      this.company_id = this.Company_list.filter(
        (item) => item.id == id
      )[0].company;
      this.company_id_id = this.Company_list.filter(
        (item) => item.id == id
      )[0].id;
      console.log(this.company_id_id, "this.company_id_id");
    },

    // 部门名字获取
    departmentIndex(department) {
      this.department_id = this.department_list.filter(
        (item) => item.id == department
      )[0].id;
    },

    departmentNull(type) {
      if (type) {
        this.$set(this.formData, "id", "");
      }
    },
    closeDia() {
      this.formData.atclik = [];
      this.dialogTableVisible = false;
    },

    // 提交添加数据
    submitForm() {
      if (this.face_pic != "") {
        console.log(this.widthsize,'this.widthsize')
        if (this.widthsize < 750 || this.heightsize < 750) {
          this.$message.error(this.$t("validation.img_tip3"));
      } else{       
          this.$refs.formData.validate((valid) => {
            if (!valid) {
              return;
            } else {
              this.EquipmentList = [];
              this.formData.atclik.forEach((item) => {
                const data = {
                  sn: item,
                  count: "-1",
                };
                this.EquipmentList.push(data);
              });
              var data = {
                image_enc: false,
                id_no: this.formData.id_no,
                name: this.formData.name,
                face_pic: this.base64,
                employee_card_id: this.formData.employee_card_id,
                person_id: this.formData.person_id,
                company_id: this.company_id_id,
                department_id: this.department_id,
                quit: this.formData.quit,
                shop_role_id: this.formData.shop_role_id,
                description: this.formData.description,
                person_ts: this.newTime,
                // schedule_id: this.formData.schedule_id,
                image_type: this.base64type,
                // gender: this.formData.gender,
                deviceAuth: this.EquipmentList,
              };
              if(this.formData.atclik!= ""){
                employee_add(store.getters.token, data).then((res) => {
                console.log(res);
                if (res.data.status) {
                  this.$message.success(this.$t("table.add_complete"));
                  this.$emit("getLists");
                  this.dialogTableVisible = false;
                } else {
                  if (
                    res.data.data.person_id &&
                    res.data.data.person_id == -1
                  ) {
                    this.$message.error(this.$t("validation.v_worker_id"));
                  } else if (
                    res.data.data.employee &&
                    res.data.data.employee == -1
                  ) {
                    this.$message.error(this.$t("validation.v_employee_card"));
                  } else {
                    this.$message.error(this.$t("table.add_fail"));
                  }
                }
              });
            }else{
              this.$message.error(this.$t('validation.device_name'))
            }
            }
          });
        }
      } else {
        this.$message.error(this.$t("validation.img_tip4"));
      }
    },
    input(e) {
      console.log(e, "eeeeeeeeee");
    },
  },
};
</script>

<style scoped>
/* 上传图片样式 */
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 2px dashed #cccccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  margin: auto;
}
.avatar {
  position: absolute;
  left: 50%;
  top: 0;
  transform: translate(-50%,0);
  width: auto;
  height: 178px;
  display: block;
}
</style>
